// https://www.runoob.com/nodejs/nodejs-fs.html
var fs = require('fs');

fs.writeFile('a.txt', 'this is write by fs.writeFile', function(err) {
	if (err) {
		return console.error(err);
	}
	console.log('write succeed');
});


// async read
fs.readFile('a.txt', function (err, data) {
	if (err) {
		return console.error(err);
	}
	console.log('async read', data.toString());
});

var data = fs.readFileSync('a.txt');

console.log('sync read', data.toString());

fs.open('a.txt', 'r+', function(err, fd) {
	if (err) {
		return console.error(err);
	}
	console.log('open succeed');
	var buf = new Buffer.alloc(1024);
	fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {
		if (err) {
			console.log(err);
		}
		console.log(bytes, 'readed');
		if (bytes > 0) {
			console.log(buf.slice(0, bytes).toString());
		}
		fs.close(fd, function(err) {
			if (err) {
				return console.log(err);
			}
			console.log('file closed');
		});
	});
});

fs.stat('a.txt', function(err, stats) {
	console.log(stats);
	console.log('is dir', stats.isFile());
	console.log(stats.isFile());
});

// delete file
fs.unlink('b.txt', function(err) {
	if (err) {
	     return console.error(err);
	}
	console.log('delete succeed');
});

// mkdir -p
fs.mkdir('temp', {recursive: true}, (err) => {
	if (err) {
		return console.error(err);
	}
	console.log('mkdir succeed');
});

fs.rmdir('temp', err => {
	if (err) {
		return console.error(err);
	}
	console.log('rmdir');
});

fs.readdir('.', (err, files) => {
	if (err) {
		return console.error(err);
	}
	files.forEach(f => {
		console.log(f);
	});
});




